# coding: utf-8
# 存放模板渲染时使用频率高的变量.
from django.contrib.auth.models import User

from jd_asset.models import AssetInfo
from jd_oss.settings import *

from MyLdap import MyLdap

def pare_avatar(username):
    """ 处理用户头像 """
    _ldap = MyLdap.get_ldap()
    lresult = _ldap.search('(uid=%s)' % username)[0]


    if lresult.has_attribute("jpegPhoto") and lresult["jpegPhoto"]:
        avatar_path = STATIC_AVATAR_DIR + username + '.png'
        # 从ldap服务器上拉取头像保存到本地.48 x 48格式
        with open(BASE_DIR + avatar_path, mode='wb') as f:
            f.write(lresult["jpegPhoto"])
            f.flush()
    else:
        # 使用默认头像
        avatar_path = STATIC_AVATAR_DIR + STATIC_DEFAULT_AVATAR
    return avatar_path

def name_proc(request):
    username = ''
    avatar_path = ''
    is_superuser = 0
    asset_all = 0

    user_id = request.user.id

    if user_id:
        user = User.objects.get(id=user_id)
        if user:
            avatar_path = pare_avatar(user.username)
            asset_all = AssetInfo.objects.count()

    request.session.set_expiry(3600)

    info_dic = {
                'avatar_path'    : avatar_path,
                'asset_all'      : asset_all
                }

    return info_dic
